#!/bin/bash
echo "which adb: $(which adb)"

mkdir -p /tmp/logs 

arg0=$(basename $0)
if [ $arg0 = "alvs" ]; then
    if [ -z "$ADB" ]; then
        ADB="adbs"
    fi
    file_logcat=/tmp/logs/adbs
elif [ "$arg0" = "alv" ]; then
    if [ -z "$ADB" ]; then
        ADB="adb"
    fi
    file_logcat=/tmp/logs/logcat
fi
file_dmesg=/tmp/logs/dmesg

$ADB wait-for-device
now_dev=$(date -u -d "@$(adb shell date +%s)" +%m%d_%H%M%S)
now_host=$(date +%m%d_%H%M%S).$(date +%N | cut -c -3)
now_host_s=$(date +%s)
#file_logcat=$(mktemp --tmpdir=/tmp/logs logcat_$(date +%m%d_%H%M%S).$(date +%N).XXX)
#file_dmesg=$(mktemp --tmpdir=/tmp/logs dmesg_$(date +%m%d_%H%M%S).$(date +%N).XXX)
pid_dmesg=""
TMPFILE_PROP=$(mktemp)

function on_done() {
    rm -f $TMPFILE_PROP

    #if logcat file size is 0, then rm useless file(maybe generated by alv -c)
    if [ $(wc $file_logcat | awk '{print $1}') = "0" ]; then
        rm $file_logcat
        rm $file_dmesg
    else
        suffix="$(($(date +%s)-$now_host_s))s"
        mv $file_logcat ${file_logcat}-$suffix
        mv $file_dmesg $file_dmesg-$suffix
        echo -e "\n\\033[41;37m$file_logcat-$suffix\\033[0m" 1>&2
        echo -e "\\033[41;37m$file_dmesg-$suffix\\033[0m" 1>&2
    fi

    [ -n "$pid_dmesg" ] && (ps -ef | grep -v grep | grep -q $pid_dmesg) && kill -9 $pid_dmesg

    exit 0
}

function num_devices() {
    echo $($ADB devices  | sed -e '/^$/d'| grep -v 'List of devices attached' | wc -l)
}

function get_prop {
    cat $TMPFILE_PROP | grep "\[$1\]" | awk -F"[\[\]]" '{print $(NF-1)}'
}

trap 'on_done' SIGINT SIGTERM

$ADB shell getprop > $TMPFILE_PROP
build_product=$(get_prop "ro.build.product")
build_id=$(get_prop "ro.build.id")
build_type=$(get_prop "ro.build.type")
android_serial="$ANDROID_SERIAL"
if [ -z "$android_serial" ]; then
    android_serial=$(get_prop "ro.serialno")
fi
info="${now_host}_${build_product}_${android_serial}_${build_id}_${build_type}_${now_dev}"

file_logcat=${file_logcat}_${info}
file_dmesg=${file_dmesg}_${info}

touch $file_logcat
touch $file_dmesg

$ADB shell uptime > $file_dmesg
$ADB shell cat /proc/kmsg >> $file_dmesg &
pid_dmesg=$!

#adb wait-for-device && adb logcat -v time $* | tee $file_logcat
$ADB logcat -v time $* | tee $file_logcat

on_done

exit 0
